package mongodb.homework.week.three.one;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import org.codehaus.jackson.map.ObjectMapper;

import util.DBUtil;
import bean.Score;
import bean.Student;

import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;

public class HW31 {

	/**
	 * @param args
	 * @throws UnknownHostException
	 */
	public static void main(String[] args) throws UnknownHostException {

		DBCollection studentsCollection = DBUtil.getCollection("school",
				"students");

		// get all students
		DBCursor dbCursor = studentsCollection.find();
		List<Student> students = getPojo(dbCursor);
		//Collections.sort(students, new StudentIdComparator());
		print(students);	
}

	private static void print(List<Student> students) {
		Iterator<Student> iterator = students.iterator();
		while (iterator.hasNext()) {
			Student student = (Student) iterator.next();
			System.out.println(student);
		}
		System.out.println("");
	}

	private static List<Student> getPojo(DBCursor dbCursor) {
		ObjectMapper mapper = new ObjectMapper();
		List<Student> students = new ArrayList<Student>();
		while (dbCursor.hasNext()) {
			students.add(convertToPojo(mapper, dbCursor.next()));
		}
		return students;
	}

	private static Student convertToPojo(ObjectMapper mapper, DBObject obj) {
		try {
			Student student = mapper.readValue(obj.toString(), Student.class);
			List<Score> scores = student.getScores();
			scores.remove(getLowestHomeworkScore(scores));
			student.setScores(scores);
			return student;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	private static Score getLowestHomeworkScore(List<Score> scores) {
		List<Score> homeworkScores = new ArrayList<Score>();
		for (Score score : scores) {
			if (score.getType().equals("homework")) {
				homeworkScores.add(score);
			}
		}
		Collections.sort(homeworkScores, new HomeworkComparator());
		return homeworkScores.get(0);
	}

}

class StudentIdComparator implements Comparator<Student> {

	@Override
	public int compare(Student student1, Student student2) {
		return student1.get_id().compareTo(student2.get_id());
	}
}

class HomeworkComparator implements Comparator<Score>{

	@Override
	public int compare(Score score1, Score score2) {
		return Double.compare(score1.getScore(), score2.getScore());
	}
	
}
